package algorithm.mycode;


public class BinarySearchExits {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
        System.out.println(binarraySearchExistByRecursion(arr, 13));
    }

    public static boolean binarraySearchExistByIteration(int[] arr, int val) {
        if ((arr == null) || (arr.length == 0)) {
            return false;
        }
        int L = 0;
        int R = arr.length - 1;
        int mid = 0;
        while (L < R) {
            mid = L + ((R - L) >> 1);
            if (arr[mid] == val) {
                return true;
            } else if (arr[mid] > val) {
                R = mid - 1;
            } else {
                L = mid + 1;
            }
        }
        return arr[L] == val;
    }

    public static boolean binarraySearchExistByRecursion(int[] arr, int val) {
        if ((arr == null) || (arr.length == 0)) {
            return false;
        }
        return binarraySearchExistByRecursion(arr, 0, arr.length - 1, val);
    }

    public static boolean binarraySearchExistByRecursion(int[] arr, int L, int R, int val) {
        if (L < R) {
            int mid = L + ((R - L) >> 1);
            if (arr[mid] == val) {
                return true;
            } else if (arr[mid] > val) {
                return binarraySearchExistByRecursion(arr, L, mid - 1, val);
            } else {
                return binarraySearchExistByRecursion(arr, mid + 1, R, val);
            }
        }
        return arr[L] == val;
    }
}
